package cmd

import (
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/spf13/cobra"
)

func daemon_command(url string, cmd *cobra.Command, args []string) {
	client := http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Printf("创建请求失败: %v\n", err)
		return
	}

	q := req.URL.Query()
	name, _ := cmd.Flags().GetString("name")
	q.Add("name", name)
	req.URL.RawQuery = q.Encode()

	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("请求失败: %v\n", err)
		return
	}
	defer resp.Body.Close()
	buf, _ := ioutil.ReadAll(resp.Body)
	fmt.Print(string(buf))
}

var daemonStartCmd = &cobra.Command{
	Use: "start",
	Run: func(cmd *cobra.Command, args []string) {
		daemon_command(cmd_url_prefix+"/api/daemon/start", cmd, args)
	},
}

var daemonStopCmd = &cobra.Command{
	Use: "stop",
	Run: func(cmd *cobra.Command, args []string) {
		daemon_command(cmd_url_prefix+"/api/daemon/stop", cmd, args)
	},
}

var daemonStatusCmd = &cobra.Command{
	Use: "status",
	Run: func(cmd *cobra.Command, args []string) {
		daemon_command(cmd_url_prefix+"/api/daemon/status", cmd, args)
	},
}

// serviceCmd represents the service command
var daemonCmd = &cobra.Command{
	Use: "daemon",
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}

func init() {
	daemonCmd.AddCommand(daemonStartCmd)
	daemonCmd.AddCommand(daemonStopCmd)
	daemonCmd.AddCommand(daemonStatusCmd)

	daemonStartCmd.Flags().String("name", "", "service name")
	daemonStopCmd.Flags().String("name", "", "service name")
	daemonStatusCmd.Flags().String("name", "", "service name")
	rootCmd.AddCommand(daemonCmd)
}
